package com.animatron.sample.client.tree.json;

import com.animatron.sample.client.tree.node.Node;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.Window;

public class JsonLoader
{
	String jsonString;
	Node root;

	public JsonLoader(String jsonString, Node root)
	{
		super();
		this.jsonString = jsonString;
		this.root = root;
	}

	public void load()
	{
		try
		{
			JsArray<JsonNodeData> items = getNodes(jsonString);
			sync(items,root);
		}
		catch(Exception e)
		{
			Window.alert(jsonString + "\r\nParse error : " + e.getMessage());
		}
	}

	private void sync(JsArray<JsonNodeData> items, Node rootNode)
	{
		rootNode.getItems().clear();
		for(int i = 0;i<items.length();i++)
		{
			Node node = new Node();
			node.setName(items.get(i).getName());
			sync(items.get(i).getChildren(), node);
			rootNode.getItems().add(node);
		}
	}

	private final native JsArray<JsonNodeData> getNodes(String js) /*-{
		return eval(js);
	}-*/;
}
